<template>
  <div class="home-container">
    <!-- 顶部搜索栏 -->
    <div class="search-container">
      <el-input 
        v-model="searchQuery" 
        placeholder="搜索提示词..." 
        class="search-input"
      >
        <template #prefix>
          <Search />
        </template>
      </el-input>
    </div>

    <!-- 提示词展示区域 -->
    <div class="prompt-container">
      <el-input
        v-model="currentPrompt.prompt"
        type="textarea"
        placeholder="请输入或编辑提示词"
        class="prompt-textarea"
        :rows="2"
        :readonly="false"
      />
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左右切换按钮 -->
      <el-button 
        class="nav-button left-button"
        @click="prevPage"
        :disabled="currentPage <= 1"
      >
        <ArrowLeft />
      </el-button>

      <!-- 平台展示区域 -->
      <div class="platforms-container">
        <!-- 显示从Square页面传来的图片 -->
        <div v-if="currentPrompt.previewImage" class="preview-card">
          <img :src="currentPrompt.previewImage" :alt="currentPrompt.prompt" style="max-width:100%; height:250px; object-fit:cover; border-radius:8px;" />
          <div class="prompt-text">{{ currentPrompt.prompt.substring(0, 100) }}{{ currentPrompt.prompt.length > 100 ? '...' : '' }}</div>
        </div>
        <!-- 原始的平台展示 -->
        <div v-else class="platforms-grid">
          <div 
            v-for="platform in platforms" 
            :key="platform.id"
            class="platform-card"
            @click="showPreview(platform)"
          >
            <div class="platform-image">{{ platform.name }}</div>
            <div class="platform-name">{{ platform.name }}</div>
          </div>
        </div>
      </div>

      <el-button 
        class="nav-button right-button"
        @click="nextPage"
        :disabled="currentPage >= totalPages"
      >
        <ArrowRight />
      </el-button>
    </div>

    <!-- 交互功能区域 -->
    <div class="interaction-area">
      <el-button 
        class="interaction-button comment-button"
        @click="toggleCommentArea"
        :type="showComments ? 'primary' : ''"
      >
        评论 {{ comments.length > 0 ? `(${comments.length})` : '' }}
      </el-button>
      <el-button 
        class="interaction-button run-button"
        @click="runPrompt"
        type="primary"
      >
        <VideoPlay /> 运行
      </el-button>
      <el-button 
        class="interaction-button collect-button"
        @click="toggleCollect"
        :type="isCollected ? 'primary' : ''"
      >
        <template #icon>
          <CollectionTag v-if="isCollected" />
          <Collection v-else />
        </template>
        收藏
      </el-button>
    </div>

    <!-- 评论区域 -->
    <div v-show="showComments" class="comments-area">
      <div class="comments-header">
        <h3>评论区</h3>
        <el-input 
          v-model="newComment"
          placeholder="写下你的评论..."
          @keyup.enter="addComment"
          show-word-limit
          maxlength="200"
          class="comment-input"
        />
        <el-button @click="addComment" type="primary">发表评论</el-button>
      </div>
      <div class="comments-list">
        <div v-for="comment in comments" :key="comment.id" class="comment-item">
          <div class="comment-author">{{ comment.author }}</div>
          <div class="comment-content">{{ comment.content }}</div>
          <div class="comment-time">{{ formatTime(comment.time) }}</div>
        </div>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog 
      :title="previewPlatform.name || '平台预览'" 
      v-model="showPreviewDialog"
      width="70%"
    >
      <div class="preview-content">
        <div class="preview-prompt">
          <div class="preview-prompt-title">提示词</div>
          <div class="preview-prompt-text">{{ currentPrompt.prompt }}</div>
        </div>
        <div class="preview-image" v-if="previewPlatform.name">
          {{ previewPlatform.name }}
        </div>
        <div v-else-if="currentPrompt.previewImage" class="preview-image" :style="{ backgroundImage: `url(${currentPrompt.previewImage})` }"></div>
        <div v-else class="preview-image">默认预览</div>
        <div class="preview-info">
          <h3>{{ previewPlatform.name }}</h3>
          <p>生成内容：基于提示词的AI生成效果</p>
          <p>数据更新时间：{{ previewPlatform.updateTime || new Date().toLocaleString() }}</p>
          <p>IP地址：{{ previewPlatform.ip || '172.24.0.3' }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { 
  Search, ArrowLeft, ArrowRight, 
  VideoPlay, Collection, CollectionTag 
} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

export default {
  name: 'Home',
  components: {
    Search,
    ArrowLeft,
    ArrowRight,
    VideoPlay,
    Collection,
    CollectionTag
  },
  setup() {
    const route = useRoute()
    // 搜索查询
    const searchQuery = ref('')
    
    // 当前页码
    const currentPage = ref(1)
    
    // 三个固定平台
    const platforms = ref([
      { id: 1, name: '豆包', updateTime: '2025-11-03 15:59', ip: '172.24.0.3' },
      { id: 2, name: '通义', updateTime: '2025-11-03 15:58', ip: '172.24.0.3' },
      { id: 3, name: '即梦', updateTime: '2025-11-03 15:57', ip: '172.24.0.3' }
    ])
    
    // 提示词数据列表
    const prompts = ref([
      { id: 1, prompt: '一只可爱的小猫在阳光下睡觉' },
      { id: 2, prompt: '城市夜景，霓虹灯闪烁' },
      { id: 3, prompt: '山水画，宁静的湖泊和远山' },
      { id: 4, prompt: '未来科技城市，飞行汽车和高楼' }
    ])
    
    // 当前提示词 - 使用响应式引用确保可编辑性
    const currentPrompt = ref({
      id: prompts.value[0].id,
      prompt: prompts.value[0].prompt,
      previewImage: ''
    })
    
    // 预览平台（提供初始值避免页面空白）
    const previewPlatform = ref({ name: '' })
    
    // 从路由参数中获取提示词和预览图
    const initFromRoute = () => {
      try {
        if (route.query.prompt) {
          // 将传入的提示词添加到提示词列表
          const newPrompt = {
            id: Date.now(), // 生成唯一ID
            prompt: String(route.query.prompt),
            previewImage: String(route.query.previewImage || '')
          }
          prompts.value.unshift(newPrompt)
          currentPrompt.value = newPrompt
          currentPage.value = 1 // 设置为第一页
        }
      } catch (error) {
        console.error('处理路由参数时出错:', error)
        // 即使出错也要确保页面有内容显示
        if (!currentPrompt.value.prompt) {
          currentPrompt.value = {
            ...prompts.value[0],
            previewImage: ''
          }
        }
      }
    }
    
    // 初始化页面数据
    initFromRoute()
    
    // 计算总页数（基于提示词数量）
    const totalPages = computed(() => {
      return prompts.value.length
    })
    
    // 下一页
    const nextPage = () => {
      if (currentPage.value < totalPages.value) {
        currentPage.value++
        // 切换到对应页的提示词（根据索引而不是ID）
        const newPrompt = prompts.value[currentPage.value - 1]
        if (newPrompt) {
          currentPrompt.value = { ...newPrompt }
        }
      }
    }
    
    // 上一页
    const prevPage = () => {
      if (currentPage.value > 1) {
        currentPage.value--
        // 切换到对应页的提示词（根据索引而不是ID）
        const newPrompt = prompts.value[currentPage.value - 1]
        if (newPrompt) {
          currentPrompt.value = { ...newPrompt }
        }
      }
    }
    
    // 收藏状态
    const isCollected = ref(false)
    
    // 运行提示词 - 自动打开多个网站并传递提示词
    const runPrompt = () => {
      const promptText = currentPrompt.value.prompt;
      if (!promptText) {
        alert('请先输入提示词！');
        return;
      }

      // 编码提示词用于URL参数
      const encodedPrompt = encodeURIComponent(promptText);
      
      // 定义支持的AI生成网站列表及其URL模板
      const aiPlatforms = [
        {
          name: 'DALL-E (OpenAI)',
          url: `https://labs.openai.com/dalle?prompt=${encodedPrompt}`
        },
        {
          name: 'Midjourney (Discord)',
          url: 'https://discord.com/channels/@me' // Midjourney需要在Discord中使用
        },
        {
          name: 'Stable Diffusion (Hugging Face)',
          url: `https://huggingface.co/spaces/stabilityai/stable-diffusion`
        },
        {
          name: 'Craiyon (前DALL-E Mini)',
          url: `https://www.craiyon.com/?prompt=${encodedPrompt}`
        }
      ];

      // 显示确认对话框
      const confirmation = confirm(`即将在新标签页中打开以下${aiPlatforms.length}个网站：\n${aiPlatforms.map(p => p.name).join('\n')}\n\n提示词已复制到剪贴板，请在各网站中粘贴使用。`);
      
      if (confirmation) {
        // 复制提示词到剪贴板
        navigator.clipboard.writeText(promptText).then(() => {
          console.log('提示词已复制到剪贴板');
          
          // 打开每个平台的网站
          aiPlatforms.forEach(platform => {
            // 使用延时打开，避免浏览器阻止多个弹窗
            setTimeout(() => {
              window.open(platform.url, '_blank');
            }, 300);
          });
          
          // 显示成功提示
          alert(`已成功打开${aiPlatforms.length}个AI生成平台网站！提示词已复制到剪贴板，请在各网站中粘贴使用。`);
        }).catch(err => {
          console.error('复制到剪贴板失败:', err);
          // 即使复制失败，仍然尝试打开网站
          aiPlatforms.forEach(platform => {
            setTimeout(() => {
              window.open(platform.url, '_blank');
            }, 300);
          });
          alert(`已打开网站，但复制提示词失败，请手动复制：${promptText}`);
        });
      }
    }
    
    // 切换收藏
    const toggleCollect = () => {
      isCollected.value = !isCollected.value
    }
    
    // 显示评论区
    const showComments = ref(false)
    
    // 切换评论区显示
    const toggleCommentArea = () => {
      showComments.value = !showComments.value
    }
    
    // 评论数据
    const comments = ref([])
    
    // 新评论内容
    const newComment = ref('')
    
    // 添加评论
    const addComment = () => {
      if (newComment.value.trim()) {
        comments.value.push({
          id: Date.now(),
          author: '用户' + Math.floor(Math.random() * 1000),
          content: newComment.value,
          time: new Date()
        })
        newComment.value = ''
      }
    }
    
    // 格式化时间
    const formatTime = (time) => {
      return new Date(time).toLocaleString()
    }
    
    // 预览平台已经在顶部定义并初始化
    const showPreviewDialog = ref(false)
    
    // 显示平台预览
    const showPreview = (platform) => {
      previewPlatform.value = { ...platform }
      showPreviewDialog.value = true
      console.log('Showing preview for platform:', platform.name)
    }
    
    return {
      searchQuery,
      currentPage,
      totalPages,
      platforms,
      currentPrompt,
      nextPage,
      prevPage,
      isCollected,
      toggleCollect,
      runPrompt,
      showComments,
      toggleCommentArea,
      comments,
      newComment,
      addComment,
      formatTime,
      previewPlatform,
      showPreviewDialog,
      showPreview
    }
  }
}
</script>

<style scoped>
/* 继承自App.vue的样式 */
.home-container {
  padding: 0;
}

/* 主预览图样式 */
.main-preview-image {
  width: 100%;
  height: 300px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #666;
  background-color: #f0f0f0;
  transition: all 0.3s ease;
}

.main-preview-image:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 预览容器样式 */
.preview-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 主内容区域样式 - 已在上方定义 */

/* 平台容器样式 */
.platforms-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 600px;
}

/* 预览卡片样式 */
.preview-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  transition: transform 0.2s;
}

.preview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

/* 提示词文本样式 */
.prompt-text {
  margin-top: 15px;
  text-align: center;
  color: #333;
  font-size: 14px;
  line-height: 1.5;
}

/* 平台网格样式 */
.platforms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  width: 100%;
}

/* 平台卡片样式 */
.platform-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #eaeaea;
}

.platform-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-color: #409EFF;
}

/* 平台图片占位样式 */
.platform-image {
  width: 100px;
  height: 100px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 10px;
  font-size: 20px;
  color: #606266;
}

/* 平台名称样式 */
.platform-name {
  font-size: 14px;
  color: #303133;
  margin-top: 10px;
}
</style>